package i2.application.checklist.services.impl;

import i2.application.checklist.dao.CheckListDao;
import i2.application.checklist.dao.QuestionDao;
import i2.application.checklist.entities.Categorie;
import i2.application.checklist.entities.CheckList;
import i2.application.checklist.entities.Question;
import i2.application.checklist.entities.Rapport;
import i2.application.checklist.entities.Reponse;
import i2.application.checklist.services.CheckListService;
import i2.application.fmw.aspects.Validation;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class CheckListServiceImpl implements CheckListService {

	private static final Logger logger = LoggerFactory.getLogger(CheckListServiceImpl.class);
	
	private QuestionDao questionDao;

	private CheckListDao checkListDao;
	
	@Override
	public List<Question> getQuestionListByCategorie(Categorie categorie) {
		return questionDao.findAllByCategorie(categorie);
	}

	@Override
	public void setQuestionDao(QuestionDao questionDao) {
		this.questionDao = questionDao;
	}

	@Override
	public List<Reponse> remplirReponses(List<Reponse> reponseList) {
		
		for (Reponse reponse : reponseList) {
			logger.debug("réponse avant : {}", reponse);
			reponse.setQuestion(questionDao.findById(reponse.getQuestion().getId()));
			logger.debug("réponse après : {}", reponse);
		}
		
		return reponseList;
	}

	@Override
	@Validation
	public void createCheckList(CheckList checkList) {
		checkListDao.add(checkList);
	}


	@Override
	public CheckList getCheckList(CheckList checkList) {
		return checkListDao.findWithCompleteLivraison(checkList.getId());
	}

	@Override
	@Validation
	public CheckList updateCheckList(CheckList checkList) {
		
		if (checkList.isDone()) {
			
			Rapport rapport = analyseReponses(checkList);
			
			checkList.setRapport(rapport);
		}
		
		return checkListDao.update(checkList);
	}
	
	@Override
	public Rapport analyseReponses(CheckList checkList) {
		Rapport rapport = new Rapport();
		// TODO rajouter un statut au rapport
		for (Reponse reponse : checkList.getReponseList()) {
			if (!reponse.isValid()) {
				logger.warn("l'analyse des réponses à trouver une alerte");
				rapport.addAlerte(reponse.getQuestion().getAlerte());
			}
		}
		
		return rapport;
	}
	
	@Override
	public void setCheckListDao(CheckListDao checkListDao) {
		this.checkListDao = checkListDao;
	}



	

}
